package com.aiyige.page.my.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.apiengine.ActionEngine;
import com.aiyige.base.eventbus.EventBuySuccess;
import com.aiyige.base.eventbus.EventOrderChanged;
import com.aiyige.city.model.City;
import com.aiyige.im.SessionHelper;
import com.aiyige.model.AgreementBackup;
import com.aiyige.model.OperationModel;
import com.aiyige.model.OrderEntity;
import com.aiyige.model.Subject;
import com.aiyige.model.User;
import com.aiyige.model.enums.GoodsType;
import com.aiyige.model.eshop.DiscountsBackup;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.moment.entity.MajorCourse;
import com.aiyige.model.request.BuyerOrderActionRequest;
import com.aiyige.model.request.OrderDetailRequest;
import com.aiyige.model.request.OrderStatusEnum;
import com.aiyige.page.detail.dialog.DialogSafeguard;
import com.aiyige.page.my.order.dialog.ConfirmInClassDialog;
import com.aiyige.page.my.order.orderDetail.OrderDetailManager;
import com.aiyige.page.pay.model.OrderModel;
import com.aiyige.page.webview.WebViewPage;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.MomentUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TimeUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.widget.LabelImageView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.vondear.rxtools.RxClipboardTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 订单详情页（聚合了买家、卖家、H5跳转）
 */
@Route(path = ARouterConfig.OrderDetailPage)
public class OrderDetailPage extends BaseActivity {

    @BindView(R.id.iv_cover)
    LabelImageView ivCover;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    //    @BindView(R.id.tv_tag)
//    TextView tvTag;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_pay_amount_value)
    TextView tvPayAmountValue;
    @BindView(R.id.tv_pay_amount)
    TextView tvPayAmount;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.tv_order_status_value)
    TextView tvOrderStatusValue;
    @BindView(R.id.tv_order_id)
    TextView tvOrderId;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;

    @BindView(R.id.tv_order_mode_of_payment)
    TextView tvOrderModeOfPayment;


    @BindView(R.id.tv_service_number)
    TextView tvServiceNumber;


    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;


    @BindView(R.id.ll_order_detail)
    LinearLayout llOrderDetail;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rl_order_content)
    RelativeLayout rlOrderContent;
    @BindView(R.id.tv_content_count)
    TextView tvContentCount;

    @BindView(R.id.rl_title_layout)
    RelativeLayout rlTitleLayout;
    @BindView(R.id.ll_safeguard)
    LinearLayout safeguardContentLayout;

    @BindView(R.id.tv_city_and_start_date)
    TextView tvCityAndStartDate;

    @BindView(R.id.ll_city)
    RelativeLayout rlCityAndStartDate;
    @BindView(R.id.tv_price)
    TextView tvPrice;

    @BindView(R.id.tv_lineation_price)
    TextView tvLinePrice;

    @BindView(R.id.rl_price)
    RelativeLayout rlPrice;


    @BindView(R.id.ll_seller_detail)
    LinearLayout llSellerDetail;

    @BindView(R.id.rl_call)
    RelativeLayout rlCall;

    @BindView(R.id.rl_im)
    RelativeLayout rlIm;


    @BindView(R.id.rl_service)
    RelativeLayout rlService;


//    @BindView(R.id.tv_order_cancel)
//    TextView tvOrderCancel;

//    @BindView(R.id.tv_pay_now)
//    TextView tvPayNow;

//    @BindView(R.id.tv_order_delete)
//    TextView tvOrderDelete;


    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_user_phone_value)
    TextView tvUserPhonePhone;
    @BindView(R.id.tv_source_value)
    TextView tvSourceValue;
    @BindView(R.id.tv_source_url_value)
    TextView tvSourceUrlValue;

    @BindView(R.id.tv_coupon_prie)
    TextView tvCouponPrice;

    @BindView(R.id.tv_coupon_name)
    TextView tvCouponName;


    @BindView(R.id.rl_operation)
    RelativeLayout rlOperationList;

    @BindView(R.id.ll_operation_list)
    LinearLayout llOperationList;

    @BindView(R.id.tv_refund_status)
    TextView tvRefundStatus;


    @BindView(R.id.consumer_protection_plan)
    View consumerProtectionPlan;


    @BindView(R.id.tv_order_id_copy)
    TextView tvIdCopy;

    @BindView(R.id.rl_coupon)
    RelativeLayout rlCoupon;

    @BindView(R.id.tv_service_charge)
    TextView tvServiceCharge;


//    @BindView(R.id.rl_seller_head_layout)
//    RelativeLayout rlSellerHeadLayout;

//    @BindView(R.id.rl_seller_head_layout_temp)
//    RelativeLayout rlSellerHeadLayoutTemp;



    @Autowired
    public String orderId;


    private OrderEntity detailEntity;

    @Autowired
    public boolean isBuyer = true;

    @Autowired
    public boolean isOrderCodeRequest;// 是否根据orderCode查询，默认是orderId


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_order_detail);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        setAutoRegisterEventBus(true);
        requestData();
    }


    private void requestData() {
        showLoading();
        OrderDetailManager.getInstance().requestOrderDetail(isBuyer ? OrderDetailRequest.type_buyer : OrderDetailRequest.type_seller, isOrderCodeRequest, orderId, new OrderDetailManager.OrderDetailCallback() {
            @Override
            public void success(OrderEntity orderEntity) {
                hideLoading();
                detailEntity = orderEntity;
                fillViews();
            }
            @Override
            public void failed() {
                hideLoading();
                finish();
            }
        });
    }

    private void fillViews() {
        if (detailEntity == null) {
            return;
        }
        detailEntity.setBuyer(isBuyer);
        Glide.with(this).load(detailEntity.getCover().get(0)).into(ivCover.getImageView());
        GlideUtil.with(this).small().loadAvatar(isBuyer ? detailEntity.getSellerAvatar() : detailEntity.getBuyerAvatar())
                .into(ivHead);
        tvTitle.setText(detailEntity.getTitle());
        ivCover.setLabel(GoodsType.getValueByKey(detailEntity.getGoodsType()));
        tvPayAmountValue.setText(StringUtils.priceFormat(detailEntity.getAmount()));
        tvOrderTime.setText(getResources().getString(R.string.order_time_value, TimeUtils.dateToYYYYMMDDHHSS(detailEntity.getCreateTime())));
        tvOrderStatus.setText(getResources().getString(R.string.order_status_value, ""));
        tvOrderStatusValue.setText(OrderStatusEnum.getValueByKey(detailEntity.getStatus()));
        tvOrderId.setText(getResources().getString(R.string.order_id_value, detailEntity.getOrderCode() + ""));
        tvName.setText(isBuyer ? detailEntity.getSellerName() : detailEntity.getBuyerName());
//        tvServicePhone.setText(getResources().getString(R.string.service_phone_value,detailEntity.getSellerMobile()));
        tvCount.setText("x" + detailEntity.getNum());
        tvContentCount.setVisibility(detailEntity.getVideoStages() > 0 ? View.VISIBLE : View.INVISIBLE);
        tvContentCount.setText(getString(R.string.content_count_value, detailEntity.getVideoStages() + ""));


        tvLinePrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvLinePrice.setVisibility(detailEntity.hasLinePrice() ? View.VISIBLE : View.GONE);
        tvLinePrice.setText("￥" + StringUtils.priceFormat(detailEntity.getSinglePrice()));
        tvPrice.setText(detailEntity.hasLinePrice() ? ("￥" + String.valueOf(detailEntity.getLinePrice())) : StringUtils.priceFormat(detailEntity.getSinglePrice()));


        tvIdCopy.setVisibility(detailEntity.isBuyer() ? View.INVISIBLE : View.VISIBLE);// 复制订单号只有卖家才有

        tvServiceCharge.setVisibility(!isBuyer && detailEntity.hasServiceCharge() ? View.VISIBLE : View.GONE);
        tvServiceCharge.setText(getResources().getString(R.string.platform_poundage_value, String.valueOf(detailEntity.getServiceCharge())));
        AgreementBackup agreementBackup = ListUtil.isEmpty(detailEntity.getAgreementBackup()) ? null : detailEntity.getAgreementBackup().get(0);
        if (agreementBackup != null && agreementBackup.getDetailBackup() != null && !ListUtil.isEmpty(agreementBackup.getDetailBackup().getGuarantee())) {
            findViewById(R.id.rl_safeguard_info).setVisibility(View.VISIBLE);
            if (safeguardContentLayout.getChildCount() == 0) {
                int max = 0;
                for (Guarantee entity : agreementBackup.getDetailBackup().getGuarantee()) {
                    if (entity == null) continue;
                    max++;
                    if (max > 4) {// 详情页外面，最多展示4个
                        break;
                    }
                    LinearLayout view = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_safeguard_tag, null);
                    TextView title = (TextView) view.findViewById(R.id.tv_tag1);
                    title.setText(entity.getName());
                    view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));
                    safeguardContentLayout.addView(view);
                }
            }
        }
//        // 培训班
//        if (detailEntity.getGoodsType() != null && detailEntity.getGoodsType().equals(Subject.training_course)) {
//            if (agreementBackup != null && !TextUtils.isEmpty(agreementBackup.getMoreBackup())) {
//                TrainingCourse trainingCourse = JsonUtil.toObject(agreementBackup.getMoreBackup(), TrainingCourse.class);
//                City city = DummyDataUtil.getCityById((agreementBackup.getCityId()));
//                if (trainingCourse != null) {
//                    tvCityAndStartDate.setText(city.getCity() + "/" + getString(R.string.start_class_info_value,trainingCourse.getStartClassTime()));
//                    tvContentCount.setVisibility(trainingCourse.getClassCount() > 0 ? View.VISIBLE : View.INVISIBLE);
//                    tvContentCount.setText(trainingCourse.getClassCount() + getString(R.string.class_count));
//                }
//
//            }
//        }
        // 专业课程
        if (detailEntity.getGoodsType() != null && detailEntity.getGoodsType().equals(Subject.major_course)) {
            if (agreementBackup != null && !TextUtils.isEmpty(agreementBackup.getMoreBackup())) {
                MajorCourse majorCourse = JsonUtil.toObject(agreementBackup.getMoreBackup(), MajorCourse.class);
                City city = DummyDataUtil.getCityById((agreementBackup.getCityId()));
                if (majorCourse != null) {
                    tvContentCount.setVisibility(majorCourse.getClassCount() > 0 ? View.VISIBLE : View.INVISIBLE);
                    tvContentCount.setText(majorCourse.getClassCount() + getString(R.string.class_count));
                    tvCityAndStartDate.setText((city == null ? "" : (city.getCity() + "/")) + getString(R.string.open_class_date_value, majorCourse.getStartClassTime()));
                }
            }
        } else if (detailEntity.getGoodsType() != null && detailEntity.getGoodsType().equals(Subject.video_course)) {
            try {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) rlPrice.getLayoutParams();
                lp.topMargin = UIHelper.dip2px(this, -63);
                rlPrice.setLayoutParams(lp);

//                LinearLayout.LayoutParams lpLine = (LinearLayout.LayoutParams) tvLinePrice.getLayoutParams();
//                lpLine.topMargin = UIHelper.dip2px(this, -63);
//                tvLinePrice.setLayoutParams(lpLine);


                RelativeLayout.LayoutParams lpCount = (RelativeLayout.LayoutParams) tvCount.getLayoutParams();
                lpCount.bottomMargin = UIHelper.dip2px(this, 15);
                tvCount.setLayoutParams(lpCount);
            } catch (Exception e) {
                Log.i("", "" + e.toString());
            }
            rlCityAndStartDate.setVisibility(View.INVISIBLE);
            tvContentCount.setVisibility(detailEntity.getVideoStages() > 0 ? View.VISIBLE : View.INVISIBLE);
            tvContentCount.setText(getString(R.string.content_count_value, detailEntity.getVideoStages() + ""));
        }


        OrderActionUtils itemDataUtils = new OrderActionUtils();

        boolean isPayed = false;
        /**
         * 买家的详情页
         */
        if (isBuyer) {
            // 未付款
            if (detailEntity.getStatus() == OrderStatusEnum.STATUS_0_NOPAY.getStatus()) {
                setViewsVisiable(View.GONE, tvOrderModeOfPayment, tvServiceNumber, tvPayTime, llSellerDetail);
                setViewsVisiable(View.VISIBLE, rlService);
            }
            // 已完成、待服务
            else if (detailEntity.getStatus() == OrderStatusEnum.STATUS_1_PAYED.getStatus() || detailEntity.getStatus() == OrderStatusEnum.STATUS_3_WAITING_SHIP.getStatus()) {
                tvOrderModeOfPayment.setText(getResources().getString(R.string.order_mode_of_payment_value, detailEntity.getPayMethodString()));
                tvServiceNumber.setText(getResources().getString(R.string.service_number_value, detailEntity.getPayCode()));
                tvPayTime.setText(getResources().getString(R.string.pay_time_value, TimeUtils.dateToYYYYMMDDHHSS(detailEntity.getPayTime())));
                setViewsVisiable(View.VISIBLE, tvOrderModeOfPayment, tvServiceNumber, tvPayTime, rlService);
                setViewsVisiable(View.GONE, llSellerDetail);
                isPayed = true;
            } else {// 已取消 已关闭
                tvOrderStatus.setText(getResources().getString(R.string.order_status_value, ""));
                tvOrderStatusValue.setText(OrderStatusEnum.getValueByKey(detailEntity.getStatus()));
                setViewsVisiable(View.GONE, tvOrderModeOfPayment, tvServiceNumber, tvPayTime, llSellerDetail);
//                setViewsVisiable(View.VISIBLE,rlServicePhone);
                setViewsVisiable(View.VISIBLE, rlService);
            }


        } else {
            /**
             * 卖家的详情页
             */
            tvUsername.setText(getResources().getString(R.string.user_name_value, detailEntity.getBuyerUserName()));
            tvUserPhonePhone.setText(getResources().getString(R.string.user_phone_value, detailEntity.getBuyerMobile()));
            tvSourceValue.setText(getResources().getString(R.string.source_value, detailEntity.getSource()));
            tvSourceUrlValue.setText(getResources().getString(R.string.source_url_value, detailEntity.getSourceUrl()));
//            tvSourceUrlValue.setText(getResources().getString(R.string.source_url_value, detailEntity.getSourceUrl()));
            setViewsVisiable(View.GONE, rlService, tvSourceUrlValue);
            setViewsVisiable(View.VISIBLE, llSellerDetail);


            if (detailEntity.getStatus() == OrderStatusEnum.STATUS_1_PAYED.getStatus() || detailEntity.getStatus() == OrderStatusEnum.STATUS_3_WAITING_SHIP.getStatus()
                    || detailEntity.getStatus() == OrderStatusEnum.STATUS_5_CONFIRMED.getStatus()) {
                tvOrderModeOfPayment.setText(getResources().getString(R.string.order_mode_of_payment_value, detailEntity.getPayMethodString()));
                tvServiceNumber.setText(getResources().getString(R.string.service_number_value, detailEntity.getPayCode()));
                tvPayTime.setText(getResources().getString(R.string.pay_time_value, TimeUtils.dateToYYYYMMDDHHSS(detailEntity.getPayTime())));
                isPayed = true;
            } else { // 状态2，未支付或已取消，都不显示下面三种状态
                setViewsVisiable(View.GONE, tvOrderModeOfPayment, tvServiceNumber, tvPayTime);
            }

        }
        // 实付金额 实收金额
        String payStatusTag = getString(isBuyer ? R.string.the_amount_actually_paid : R.string.paid_in_amount);
        tvPayAmount.setText(payStatusTag);
        fillOperationLayout(llOperationList, detailEntity.getOperationList());
        consumerProtectionPlan.setVisibility(detailEntity.hasConsumptionGuarantee() ? View.VISIBLE : View.GONE);


        if (detailEntity.getDiscountsBackup() != null) {
            rlCoupon.setVisibility(View.VISIBLE);
            DiscountsBackup discountsBackup = detailEntity.getDiscountsBackup();
            tvCouponPrice.setText("- ￥" + discountsBackup.getDiscount());
            tvCouponName.setText(discountsBackup.getDescribe() + "");
        } else {
            rlCoupon.setVisibility(View.GONE);
        }
    }


    private void fillOperationLayout(LinearLayout linearLayout, List<OperationModel> list) {
        if (!ListUtil.isEmpty(detailEntity.getOperationList())) {
            linearLayout.removeAllViews();
            for (final OperationModel operation : list) {
                View item = LayoutInflater.from(this).inflate(R.layout.item_operation_button, null);
                TextView itemOperation = (TextView) item.findViewById(R.id.tv_operation);
                if (operation.getOperationKey().equals(OperationModel.kImmediatePay)) {
                    itemOperation.setBackgroundResource(R.drawable.aiyige_green_selector);
                    itemOperation.setTextColor(ContextCompat.getColor(this, R.color.white));
                }
                itemOperation.setText(OperationModel.getValue(operation.getOperationKey()));
                itemOperation.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (operation.getOperationKey().equals(OperationModel.kCancelOrder)) {//取消订单
                            cancelOrderDialog();
                        } else if (operation.getOperationKey().equals(OperationModel.kImmediatePay)) {//立即支付
                            orderPay();
                        } else if (operation.getOperationKey().equals(OperationModel.kApplyRefund)) {//申请退款
                            ARouter.getInstance().build(ARouterConfig.RefundApplyForPage).withParcelable("orderEntity", detailEntity).navigation();
                        } else if (operation.getOperationKey().equals(OperationModel.kConfirmClassed)) {//确认上课
                            ConfirmInClassDialog.newInstance(detailEntity.getOrderId()).setListener(new ConfirmInClassDialog.Listener() {
                                @Override
                                public void onConfirmClassed(OrderEntity orderEntity) {
                                    detailEntity = orderEntity;
                                    fillViews();
                                }
                            }).show(getSupportFragmentManager(), "");
                        } else if (operation.getOperationKey().equals(OperationModel.kRefundDetail)) {//订单详情
                            ARouter.getInstance().build(ARouterConfig.RefundApplyDetailPage).withString("refundId", detailEntity.getRefundId()).withBoolean("isBuyer", isBuyer).navigation();
                        } else if (operation.getOperationKey().equals(OperationModel.kDeleteOrder)) {//删除订单
                            deleteOrderDialog();
                        }
                        // 卖家处理退款申请
                        else if (operation.getOperationKey().equals(OperationModel.kProcessRefund)) {
                            ARouter.getInstance().build(ARouterConfig.RefundDisposePage).withParcelable("orderEntity", detailEntity).navigation();
                        }

                    }
                });
                linearLayout.addView(item);
            }
            tvRefundStatus.setText(detailEntity.getRefundStatusString());
        } else {
            linearLayout.setVisibility(View.GONE);
            rlOperationList.setVisibility(View.GONE);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventOrderChanged(EventOrderChanged event) {
        if (event == null || event.getOrderEntity() == null) {
            return;
        }
        detailEntity = event.getOrderEntity();
        fillViews();
    }

    private void setViewsVisiable(int action, View... views) {
        for (View view : views) {
            view.setVisibility(action);
        }
    }

    private void orderCancel() {
        if (detailEntity == null) {
            return;
        }
        showLoading();
        BuyerOrderActionRequest.newBuilder().id(detailEntity.getOrderId() + "").action_engine(ActionEngine.CANCEL_BY_BUYER).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (!response.isSuccessful()) {
                        throw new Exception(getString(R.string.request_failed));
                    } else {
                        requestData();
                        String json = response.body().string();
                        if (!TextUtils.isEmpty(json)) {
                            Order order = JsonUtil.toObject(json, Order.class);
                            OrderEntity orderEntity1 = new OrderEntity(order);
                            EventBus.getDefault().post(EventOrderChanged.newBuilder().orderEntity(orderEntity1).build());
                            ToastX.show(getString(R.string.order_cancelled));
                        }
                    }

                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                hideLoading();
                if (!TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEventBuss(EventBuySuccess eventBuySuccess) {
        finish();
    }

    private void orderPay() {
        if (detailEntity == null) {
            return;
        }
        User user = AccountUtil.getCurrentUser();
        if (user != null && isNull(user.getMobile())) {
            ARouter.getInstance().build(ARouterConfig.BindingPhonePage).navigation();
            return;
        }
        try {
            OrderModel orderModel = OrderModel.newBuilder()
                    .orderId(detailEntity.getOrderId())
                    .goodsId(detailEntity.getMomentId())
                    .coverUrl(detailEntity.getCover().get(0))
                    .sellerId(detailEntity.getSellerId())
                    .sellerName(detailEntity.getSellerName())
                    .subjectIndex(MomentUtil.convertSubjectToSubjectIndex(detailEntity.getGoodsType()))
                    .subject(detailEntity.getGoodsType())
                    .buyNum(detailEntity.getNum())
                    .totalPayPrice(detailEntity.getAmount())
                    .singlePrice(detailEntity.getSinglePrice())
                    .sellerAvatar(detailEntity.getSellerAvatar())
                    .totalPrice(detailEntity.getAmount())
                    .totalPayPrice(detailEntity.getAmount())
                    .source(detailEntity.getSource())
                    .sourceUrl(detailEntity.getSourceUrl())
                    .title(detailEntity.getTitle())
                    .contentCountString("")
                    .build();
            ARouter.getInstance()
                    .build(ARouterConfig.ConfirmPayPage)
                    .withParcelable("orderModel", orderModel)
                    .navigation(this, 1100);

        } catch (Exception e) {

        }
    }


    @OnClick({R.id.titleBackBtn, R.id.rl_im, R.id.rl_call, R.id.rl_order_content, R.id.rl_safeguard_info, R.id.iv_head, R.id.tv_name, R.id.tv_order_id_copy, R.id.consumer_protection_plan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.rl_call:
                if (detailEntity == null || TextUtils.isEmpty(detailEntity.getMobile())) {
                    return;
                }
                Intent intent1 = new Intent(Intent.ACTION_DIAL);
                intent1.setData(Uri.parse("tel:" + detailEntity.getMobile()));
                startActivity(intent1);
                break;
            case R.id.rl_im:
                if (detailEntity != null && !isNull(detailEntity.getSellerAccid())) {
                    SessionHelper.startP2PSession(OrderDetailPage.this, detailEntity.getSellerAccid());
                }
                break;
            case R.id.rl_order_content:
                if (detailEntity == null) {
                    return;
                }
                if (detailEntity.getGoodsType().endsWith(Subject.major_course)) {
                    Router.startAiyigeH5(detailEntity.getRouter());
                } else {
                    Router.start(detailEntity.getRouter());
                }
                break;
            case R.id.rl_safeguard_info:
                if (detailEntity == null) {
                    return;
                }
                AgreementBackup agreementBackup = ListUtil.isEmpty(detailEntity.getAgreementBackup()) ? null : detailEntity.getAgreementBackup().get(0);
                if (agreementBackup != null && agreementBackup.getDetailBackup() != null && !ListUtil.isEmpty(agreementBackup.getDetailBackup().getGuarantee())) {
                    DialogSafeguard.showAsDropDown(OrderDetailPage.this, agreementBackup.getDetailBackup().getGuarantee(), rlTitleLayout);
                }
                break;
            case R.id.iv_head:
            case R.id.tv_name:
                if (detailEntity != null && !TextUtils.isEmpty(detailEntity.getSellerId())) {
                    ARouter.getInstance().build(ARouterConfig.UserPage)
                            .withString("userId", isBuyer ? detailEntity.getSellerId() : detailEntity.getBuyerUserId())
                            .navigation();
                }
                break;
            case R.id.tv_order_id_copy:
                if (detailEntity == null) {
                    return;
                }
                RxClipboardTool.copyText(OrderDetailPage.this, detailEntity.getOrderCode());
                ToastX.show(getString(R.string.copy_clipboard));
                break;
            case R.id.consumer_protection_plan:
                WebViewPage.start(BuildConfig.cspDescriptionUrl);
                break;
        }
    }


    private void cancelOrderDialog() {
        new AlertDialog.Builder(this).setTitle(R.string.alert_cancel_order)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        orderCancel();
                    }
                })
                .setNegativeButton(R.string.back, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    private void deleteOrderDialog() {
        new AlertDialog.Builder(this).setTitle(R.string.alert_delete_order)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        orderDelete();
                    }
                })
                .setNegativeButton(R.string.back, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    private void orderDelete() {
        if (detailEntity == null || TextUtils.isEmpty(detailEntity.getOrderId())) {
            return;
        }
        showLoading();
        BuyerOrderActionRequest.newBuilder().id(detailEntity.getOrderId() + "").action_engine(ActionEngine.HIDEBY_BUYER).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (!response.isSuccessful()) {
                        throw new Exception(getString(R.string.request_failed));
                    } else {
                        detailEntity.setStatus(OrderEntity.STATUS_DELETED);
                        EventBus.getDefault().post(EventOrderChanged.newBuilder().orderEntity(detailEntity).build());
                        ToastX.show(getString(R.string.order_deleted));
                        finish();
                    }
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                hideLoading();
                if (!TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == 1100 && resultCode == RESULT_OK) {
            requestData();
        }
    }
}
